package com.banyuan.项目;

import java.awt.EventQueue;

import javax.swing.*;
import java.awt.Font;
import java.awt.Color;
import java.awt.SystemColor;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.Vector;

public class Client {

    //swing组件的相关属性；
    private JFrame frame;
    private JTextField textField;
    private JTextArea textArea;
    private JComboBox comboBox;
    private JCheckBox chckbxNewCheckBox;
    private JComboBox comboBox_1;
    private JTextPane textPane;

    //客户端设置界面；
    ClientSet clientSet = new ClientSet();

    //用户设置的属性（有默认值）；
    private String userName = "aaa";
    private String ipLocation = "localhost";
    private int port = 8080;

    //输入输出流；
    private ObjectOutputStream out;
    private ObjectInputStream in;

    //监听功能；
    private Engine engine;


    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getIpLocation() {
        return ipLocation;
    }

    public void setIpLocation(String ipLocation) {
        this.ipLocation = ipLocation;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Client window = new Client();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Client() {
        initialize();
        textArea.append("欢迎启动半圆聊天室客户端！" + "\n");
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setTitle("半圆聊天室客户端");
        frame.setBounds(100, 100, 529, 505);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnNewButton = new JButton("用户设置");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //显示用户设置的窗口；
                clientSet.setVisible(true);
            }
        });
        btnNewButton.setBounds(6, 6, 96, 29);
        frame.getContentPane().add(btnNewButton);

        JButton btnNewButton_1 = new JButton("登陆");
        btnNewButton_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //新建一个引擎；
                //利用多线程防止卡死；
                new Thread(() -> {
                    engine = new Engine();
                    //向服务器发送一个请求，表示登陆
                    //这边需要多线程吗？


                }).start();
                btnNewButton_1.setEnabled(false);
            }
        });
        btnNewButton_1.setBounds(114, 6, 96, 29);
        frame.getContentPane().add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("退出");
        btnNewButton_2.setBounds(222, 6, 96, 29);
        frame.getContentPane().add(btnNewButton_2);

        JButton btnNewButton_2_1 = new JButton("注销");
        btnNewButton_2_1.setBounds(330, 6, 96, 29);
        frame.getContentPane().add(btnNewButton_2_1);

        //文本域的显示内容；
        textArea = new JTextArea();
        JScrollPane jsp = new JScrollPane(textArea);
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jsp.setBounds(6, 40, 517, 331);
        frame.getContentPane().add(jsp);
//        textArea.setBounds(6, 40, 517, 331);
//        frame.getContentPane().add(textArea);

        JLabel label = new JLabel("发送消息至：");
        label.setBounds(6, 383, 83, 29);
        frame.getContentPane().add(label);

        comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(new String[]{"所有人"}));
        comboBox.setBounds(84, 383, 110, 27);
        frame.getContentPane().add(comboBox);

        JLabel label_1 = new JLabel("发送消息：");
        label_1.setBounds(6, 422, 83, 19);
        frame.getContentPane().add(label_1);

        //发送的过程；
        //这边用到了一个out会造成空指针异常；
        //利用一个判断语句避免发生空指针异常；
        JButton btnNewButton_3 = new JButton("发送");
        btnNewButton_3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Request request = new Request();
                //获取功能；
                request.setFunction(4);
                //获取发送者姓名；
                request.setUsername(Client.this.getUserName());
                //获取发送的消息；
                request.setMsgOut(textField.getText());
                //获取发送人；
                request.setTo((String) comboBox.getSelectedItem());
                //获取是否私聊；
                request.setAll(chckbxNewCheckBox.isSelected());
                //获取表情；
                request.setExpression((String) comboBox_1.getSelectedItem());

                if (out == null) {
                    textArea.append("未连接服务器！" + "\n");
                } else {
//                    textArea.append((String) comboBox.getSelectedItem());
//                    textArea.append(request.getMsgOut() + "\n ");
//                    textArea.append(request.getFunction() + "");
//                    textArea.append(request.isAll() + "");
                    //规定发送不要换行，显示的时候换行；
                    //对象序列化发送；
                    try {
                        out.writeObject(request);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                    //清空输入框；
                    textField.setText("");
                    //将文字打印在文本域中；
                    if (request.isAll()) {
                        if (request.getTo().equals("所有人")) {
                            if (request.getExpression().equals("无")) {
                                textArea.append("你悄悄地对大家说：" + request.getMsgOut() + "\n");
                            } else {
                                textArea.append("你（" + request.getExpression() + "）" + "悄悄地对大家说：" + request.getMsgOut() + "\n");
                            }
                        } else {
                            if (request.getExpression().equals("无")) {
                                textArea.append("你悄悄的对" + request.getTo() + "说：" + request.getMsgOut() + "\n");
                            } else {
                                textArea.append("你（" + request.getExpression() + "）" + "悄悄的对" + request.getTo() + "说：" + request.getMsgOut() + "\n");

                            }
                        }
                    } else {
                        //非私聊的过程；
                        if (request.getTo().equals("所有人")) {
                            if (request.getExpression().equals("无")) {
                                textArea.append("你对大家说：" + request.getMsgOut() + "\n");
                            } else {
                                textArea.append("你（" + request.getExpression() + "）" + "对大家说：" + request.getMsgOut() + "\n");
                            }
                        } else {
                            if (request.getExpression().equals("无")) {
                                textArea.append("你对" + request.getTo() + "说：" + request.getMsgOut() + "\n");
                            } else {
                                textArea.append("你（" + request.getExpression() + "）" + "对" + request.getTo() + "说：" + request.getMsgOut() + "\n");
                            }
                        }
                    }
                }
            }
        });
        btnNewButton_3.setBounds(406, 418, 117, 29);
        frame.getContentPane().add(btnNewButton_3);

        textField = new JTextField();
        textField.setBounds(61, 418, 345, 29);
        frame.getContentPane().add(textField);
        textField.setColumns(10);

        textPane = new JTextPane();
        textPane.setText("当前在线人数0");
        textPane.setBackground(SystemColor.window);
        textPane.setForeground(Color.LIGHT_GRAY);
        textPane.setBounds(6, 453, 507, 19);
        frame.getContentPane().add(textPane);


        JLabel label_2 = new JLabel("表情：");
        label_2.setBounds(222, 383, 83, 29);
        frame.getContentPane().add(label_2);

        comboBox_1 = new JComboBox();
        comboBox_1.setModel(new DefaultComboBoxModel(new String[]{"微笑的", "愤怒的", "悲伤的", "激动的", "平和的", "无"}));
        comboBox_1.setBounds(261, 383, 110, 27);
        frame.getContentPane().add(comboBox_1);

        chckbxNewCheckBox = new JCheckBox("悄悄话");
        chckbxNewCheckBox.setBounds(436, 383, 77, 23);
        frame.getContentPane().add(chckbxNewCheckBox);
    }

    public class Engine {
        public Engine() {
            try {
                //会连接服务端
                //将Client类中的ipLocation和port传给engine；
                Socket socket = new Socket(Client.this.getIpLocation(), Client.this.getPort());
                textArea.append("你已经进入聊天室，开始聊天吧！" + "\n");
                in = new ObjectInputStream(socket.getInputStream());
                out = new ObjectOutputStream(socket.getOutputStream());
//                textArea.append("客户端将进入发送指令的线程" + "\n");
                Request request = new Request();
                request.setFunction(1);
                request.setUsername(Client.this.getUserName());
                try {
                    out.writeObject(request);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
//                textArea.append("客户端登陆序列化已完成！" + "\n");
                new Thread(() -> {
                    try {
                        while (true) {
                            //IO阻塞 等待服务器写数据给我;
                            Response response = (Response) in.readObject();
                            switch (response.getFunction()) {
                                //第一种情况服务器的通知，服务器的群发；
                                case 1:
                                    textArea.append("服务器通知：" + response.getMsg() + "\n");
                                    break;
                                //更新客户端列表；
                                case 2:
                                    //客户端列表中的自己；
                                    Vector<String> v = response.getV();
                                    v.remove(Client.this.userName);
                                    comboBox.setModel(new DefaultComboBoxModel(v));
                                    textPane.setText("当前在线人数：" + response.getNumClient());
                                    break;
                                //私聊群发的消息；
                                case 3:
                                    if (response.getExpression().equals("无")) {
                                        textArea.append(response.getUserName() + "悄悄的对你说：" + response.getMsg() + "\n");
                                    } else {
                                        textArea.append(response.getUserName() + "（" + response.getExpression() + "）" + "悄悄的对你说：" + response.getMsg() + "\n");
                                    }
                                    break;
                                //非私聊的群发的过程；
                                case 4:
                                    if (response.getExpression().equals("无")) {
                                        textArea.append(response.getUserName() + "对大家说：" + response.getMsg() + "\n");
                                    } else {
                                        textArea.append(response.getUserName() + "（" + response.getExpression() + "）" + "对大家说：" + response.getMsg() + "\n");
                                    }
                                    break;
                                //非私聊的单独对话的群发对象过程；
                                case 5:
                                    if (response.getExpression().equals("无")) {
                                        textArea.append(response.getUserName() + "对" + response.getTo() + "说：" + response.getMsg() + "\n");
                                    } else {
                                        textArea.append(response.getUserName() + "（" + response.getExpression() + "）" + "对" + response.getTo() + "说：" + response.getMsg() + "\n");
                                    }
                                    break;
                                //非私聊的单独对话的接受者的过程；
                                case 6:
                                    if (response.getExpression().equals("无")) {
                                        textArea.append(response.getUserName() + "对你说:" + response.getMsg() + "\n");
                                    } else {
                                        textArea.append(response.getUserName() + "（" + response.getExpression() + "）" + "对你说：" + response.getMsg() + "\n");
                                    }
                                    break;

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //一个内部类用来设置用户的信息；
    public class ClientSet extends JDialog {
        private JTextField textField;
        private JTextField textField_1;
        private JTextField textField_2;

        public JTextField getTextField() {
            return textField;
        }

        public JTextField getTextField_1() {
            return textField_1;
        }

        public JTextField getTextField_2() {
            return textField_2;
        }

        /**
         * Launch the application.
         */


        /**
         * Create the dialog.
         */
        public ClientSet() {
            this.setVisible(false);
            setTitle("用户设置");
            setBounds(100, 100, 368, 231);
            getContentPane().setLayout(null);
            {
                JButton okButton = new JButton("OK");
                okButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        Client.this.setUserName(textField.getText());
                        Client.this.setIpLocation(textField_1.getText());
                        Client.this.setPort((Integer.parseInt(textField_2.getText())));
                        ClientSet.this.setVisible(false);
                    }
                });
                okButton.setBounds(85, 157, 75, 29);
                getContentPane().add(okButton);
                okButton.setActionCommand("OK");
                getRootPane().setDefaultButton(okButton);
            }
            {
                JButton cancelButton = new JButton("Cancel");
                cancelButton.addActionListener((e) -> {
                    //Cancel按钮，点击之后退出界面，但是界面还在运行；
                    ClientSet.this.setVisible(false);
                });
                cancelButton.setBounds(173, 157, 86, 29);
                getContentPane().add(cancelButton);
                cancelButton.setActionCommand("Cancel");
            }
            {
                JLabel lblNewLabel = new JLabel("请输入用户名：");
                lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
                lblNewLabel.setBounds(62, 22, 98, 29);
                getContentPane().add(lblNewLabel);
            }
            {
                textField = new JTextField();
                textField.setBounds(172, 22, 150, 28);
                getContentPane().add(textField);
                textField.setColumns(10);
            }
            {
                JLabel lblip = new JLabel("请输入IP地址：");
                lblip.setHorizontalAlignment(SwingConstants.RIGHT);
                lblip.setBounds(62, 63, 98, 29);
                getContentPane().add(lblip);
            }
            {
                JLabel lblNewLabel = new JLabel("请输入端口号：");
                lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
                lblNewLabel.setBounds(62, 104, 98, 29);
                getContentPane().add(lblNewLabel);
            }
            {
                textField_1 = new JTextField();
                textField_1.setColumns(10);
                textField_1.setBounds(172, 63, 150, 28);
                getContentPane().add(textField_1);
            }
            {
                textField_2 = new JTextField();
                textField_2.setColumns(10);
                textField_2.setBounds(172, 105, 150, 28);
                getContentPane().add(textField_2);
            }
        }

    }
}
